import aiojobs
from fastapi import FastAPI
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin

class AiojobsPluginClient(BasePlugin):
    # 设置插件默认的参数信息
    name = 'Aiojobs插件'

    def setup(self, app: FastAPI, name: str = None, *args, **kwargs):
        """插件初始化"""
        # 当期的插件实例对象赋值
        self.app = app
        self.app.aiojobs = None
        self._aiojobs = None


        # 添加在应用程序启动之前运行的函数
        @app.on_event("startup")
        async def startup_event():
            self._aiojobs = aiojobs.Scheduler()
            app.aiojobs = self._aiojobs

        # 添加在应用程序关闭时运行的函数
        @app.on_event("shutdown")
        async def shutdown_event():
            await self._aiojobs.close()

    @property
    def spawn(self):
        if  self.app.aiojobs is None:
            raise Exception('需要先初始化插件！')
        return self._aiojobs.spawn


